#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""代码编辑器组件"""

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QMessageBox
from PyQt5.QtCore import Qt, QSettings
from PyQt5.QtGui import QFont, QColor
from PyQt5.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs


class CodeEditor(QWidget):
    """代码编辑器组件"""
    
    def __init__(self):
        """初始化代码编辑器"""
        super().__init__()
        
        # 创建QScintilla编辑器
        self.editor = QsciScintilla()
        
        # 设置编辑器属性
        self.setup_editor()
        
        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(self.editor)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        
        # 加载默认代码
        self.load_default_code()
    
    def setup_editor(self):
        """设置编辑器的基本属性"""
        # 设置字体
        font = QFont("Consolas", 12)
        self.editor.setFont(font)
        
        # 设置行号
        self.editor.setMarginType(0, QsciScintilla.NumberMargin)
        self.editor.setMarginWidth(0, "000")
        self.editor.setMarginsFont(font)
        
        # 设置自动缩进
        self.editor.setAutoIndent(True)
        self.editor.setIndentationWidth(4)
        self.editor.setIndentationGuides(True)
        
        # 设置制表符转换为空格
        self.editor.setTabWidth(4)
        self.editor.setTabIndents(True)
        self.editor.setBackspaceUnindents(True)
        self.editor.setIndentationsUseTabs(False)
        
        # 设置括号匹配
        self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        
        # 设置折叠功能
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        
        # 设置自动补全
        self.editor.setAutoCompletionThreshold(1)  # 输入1个字符就开始补全
        self.editor.setAutoCompletionSource(QsciScintilla.AcsAll)
        self.editor.setAutoCompletionCaseSensitivity(False)
        self.editor.setAutoCompletionReplaceWord(True)
        
        # 设置Python语法高亮
        self.lexer = QsciLexerPython()
        self.lexer.setDefaultFont(font)
        
        # 设置语法高亮颜色
        self.setup_lexer_colors()
        
        self.editor.setLexer(self.lexer)
        
        # 设置API自动完成
        self.api = QsciAPIs(self.lexer)
        self.setup_apis()
        self.api.prepare()
    
    def setup_lexer_colors(self):
        """设置语法高亮的颜色"""
        # 设置默认文本颜色
        self.lexer.setDefaultColor(QColor(0, 0, 0))
        
        # 设置关键字颜色
        self.lexer.setColor(QColor(160, 50, 255), QsciLexerPython.Keyword)
        
        # 设置字符串颜色
        self.lexer.setColor(QColor(255, 0, 0), QsciLexerPython.DoubleQuotedString)
        self.lexer.setColor(QColor(255, 0, 0), QsciLexerPython.SingleQuotedString)
        
        # 设置注释颜色
        self.lexer.setColor(QColor(0, 128, 0), QsciLexerPython.Comment)
        self.lexer.setColor(QColor(0, 128, 0), QsciLexerPython.CommentBlock)
        
        # 设置数字颜色
        self.lexer.setColor(QColor(0, 0, 255), QsciLexerPython.Number)
        
        # 设置操作符颜色
        self.lexer.setColor(QColor(150, 150, 150), QsciLexerPython.Operator)
        
        # 设置标识符颜色
        self.lexer.setColor(QColor(0, 0, 0), QsciLexerPython.Identifier)
    
    def setup_apis(self):
        """设置API自动完成"""
        # 添加一些常用的Python函数和类
        python_apis = [
            "print", "len", "range", "list", "dict", "set", "tuple",
            "str", "int", "float", "bool", "open", "input",
            "import", "from", "def", "class", "if", "else", "elif",
            "for", "while", "return", "break", "continue", "pass",
            "try", "except", "finally", "raise", "with", "as"
        ]
        
        # 添加PyQt5常用类
        pyqt_apis = [
            "QApplication", "QMainWindow", "QWidget", "QPushButton",
            "QLabel", "QLineEdit", "QTextEdit", "QVBoxLayout",
            "QHBoxLayout", "QGridLayout", "QMessageBox", "QFileDialog"
        ]
        
        # 添加到API
        for api in python_apis + pyqt_apis:
            self.api.add(api)
    
    def load_default_code(self):
        """加载默认代码"""
        default_code = '''#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Python应用程序"""

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import Qt


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        """初始化主窗口"""
        super().__init__()
        
        # 设置窗口属性
        self.setWindowTitle("Python应用程序")
        self.resize(400, 300)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建布局
        layout = QVBoxLayout(central_widget)
        
        # 添加标签
        self.label = QLabel("欢迎使用Python应用程序！")
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)
        
        # 添加按钮
        self.button = QPushButton("点击我")
        self.button.clicked.connect(self.on_button_clicked)
        layout.addWidget(self.button)
    
    def on_button_clicked(self):
        """按钮点击事件处理"""
        self.label.setText("按钮被点击了！")


def main():
    """主函数"""
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
'''
        
        self.editor.setText(default_code)
        
    def load_file(self, file_path):
        """加载文件内容到编辑器"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            self.editor.setText(content)
            return True
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法加载文件: {str(e)}")
            return False
    
    def save_file(self, file_path):
        """保存编辑器内容到文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(self.editor.text())
            return True
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法保存文件: {str(e)}")
            return False
    
    def get_text(self):
        """获取编辑器中的文本"""
        return self.editor.text()
    
    def set_text(self, text):
        """设置编辑器中的文本"""
        self.editor.setText(text)